package com.tongda.menu.activity;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.BounceInterpolator;
import android.view.animation.RotateAnimation;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.view.animation.Animation.AnimationListener;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AbsListView;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import com.cuubonandroid.sugaredlistanimations.SpeedScrollListener;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.tongda.core.common.Constants;
import com.tongda.core.common.KernalApplication;
import com.tongda.core.enums.DinnerStatusEnum;
import com.tongda.core.enums.StatusCodeEnum;
import com.tongda.core.repository.MenuCartDao;
import com.tongda.core.repository.MenuDishCategoryDAO;
import com.tongda.core.repository.MenuDishDao;
import com.tongda.core.service.TableService;
import com.tongda.core.service.UserService;
import com.tongda.core.utils.ActivityUtil;
import com.tongda.core.utils.DishCategoryUtil;
import com.tongda.core.utils.DishUtil;
import com.tongda.core.utils.MenuDBHelper;
import com.tongda.core.utils.SharedPreferencesUtils;
import com.tongda.core.vo.Dish;
import com.tongda.core.vo.DishesCategory;
import com.tongda.core.vo.MobileRspResult;
import com.tongda.menu.R;
import com.tongda.menu.R.drawable;
import com.tongda.menu.adapter.AutoTextAdapater;
import com.tongda.menu.adapter.DishAdapter;
import com.tongda.menu.adapter.DishCategoryAdapter;
import com.tongda.menu.adapter.WaterfallAdapter;
import com.tongda.menu.huewu.pla.lib.PLA_AbsListView;
import com.tongda.menu.service.ClearMemoryService;
import com.tongda.menu.service.ClearMemoryService.ClearMemoryBinder;
import com.tongda.menu.service.SoundMusicService;
import com.tongda.menu.service.SoundMusicService.SoundMusicBinder;
import com.tongda.menu.util.ActivityMenuUtil;
import com.tongda.menu.widget.BadgeView;
import com.tongda.menu.widget.MultiColumnListView;
import com.tongda.menu.widget.MultiColumnListView.OnLoadMoreListener;



public class MainActivity extends BaseActivity {
	
	private static final String LOG_TAG = "MAINACTIVITY";
	private final int PULL_TO_REFRESH_ID = 1008611;
    public final String TABLE_NAME = "menu_cart";
    protected  MultiColumnListView mWaterfallView = null;
    protected WaterfallAdapter  mAdapter;
	private ListView dishCategory_listView;
	public DishCategoryAdapter dishCategory_adapter;
	public List<DishesCategory> dishCategoryDatas;
	public MenuDishCategoryDAO dishCategory_dao;
	private SpeedScrollListener listener;
	public MenuDishDao dish_dao;
	private AutoCompleteTextView searchDishActv;
	public DishCategoryUtil dishCategory_util;
	public DishUtil dish_util;
	private String[] dishNames;
	private AutoTextAdapater aTadapter;
	public  List<Dish> dishDatas;
	private List<Dish> dishAll;
	private ImageView tableIcon;
	private ImageView SettingIcon;
	private ImageView ListIcon;
	protected ListView mdishLv;
	public DishAdapter dishAdapter;
	private ListView dish_listView;
	private boolean mWaterFlag = true;
	private ImageView callServiceImv;
	private ImageView cartImv;
	public MenuCartDao ordered_dish_dao;
	//flag的作用是判断点进详细页面时，是从哪个分类过去的
	public boolean flag;
	public String dishCategoryId;
	
	public static int currentPosition=0;
	public BadgeView orderedNumTv;
	private LinearLayout listLy;
	private TextView tableNumTv;
	private TextView  tablePeopleNumTv;
	public KernalApplication application;
	
	public int dishCurrentPosition=0;
	public SoundPool sp;
	public int music;
	
	protected ClearMemoryService clearMemoryService;
	public boolean bound;
	
    private LinearLayout l1;
    private ExplosionView exv1;
    private AnimationDrawable exa1;
    
	protected PopupWindow popWindow;
	protected View mView;
	public boolean isClicked;
	public boolean btnisClicked;
	//这个变量是用来指定popwindow显示在哪个一级菜类的位置的变量
	public static int fatherCategoryId;
	private List<String> dinerDishesCategoryIds;
	public  int dinerDishesCount =0;
	private List<Dish> dinerDishes;
	public ImageLoader imageLoader;
	public DisplayImageOptions options;
	private BounceInterpolator bdInterpolator;
	@SuppressLint("HandlerLeak")
	Handler handler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch(msg.what){
			case Constants.DESCRIBE:
				 dialog.dismiss();
				 setBlockScreen(false);
		         dishCategory_adapter = new DishCategoryAdapter(MainActivity.this, dishCategoryDatas);
		         dishCategory_listView.setAdapter(dishCategory_adapter);
		         
		         initUIAction();
				break;
			case 5:
				final AlertDialog dialog = new AlertDialog.Builder(MainActivity.this).create();
				View dialogView = View.inflate(MainActivity.this, R.layout.dialog_cleantable, null);
				dialog.setView(dialogView,0,0,0,0);
				dialog.setCanceledOnTouchOutside(false);
				dialog.show();
				
				ImageView closeBtn = (ImageView)dialogView.findViewById(R.id.cleantable_close);
				TextView msgTv = (TextView)dialogView.findViewById(R.id.cleantable_msg);
				Button confirmBtn = (Button)dialogView.findViewById(R.id.cleantable_confirm);
				Button cancelBtn = (Button)dialogView.findViewById(R.id.cleantable_cancel);
				
				closeBtn.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						dialog.dismiss();
					}
				});
				msgTv.setText("餐台"+application.getMenuSelectedTable().getTabNo()+"确认清台？");
				confirmBtn.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						Thread clearTableThread = new Thread(new Runnable() {
							
							@Override
							public void run() {
								MobileRspResult result = TableService.cleanTable(application.getMenuSelectedTable().getTabId());
								if(result.getStatusCode().equals(StatusCodeEnum.SUCCESS.getCode())){
									application.setMenuSelectedTable(null);
									application.setMenuMainIsRefresh(true);
									dinerDishesCategoryIds=null;
									dinerDishes=null;
									dinerDishesCount=0;
									ActivityUtil.switchActivity(MainActivity.this, false, TableActivity.class);
									overridePendingTransition(R.anim.in_from_top, R.anim.out_to_bottom);
								}
							}
						});
						clearTableThread.start();
						dialog.dismiss();
					}
				});
				cancelBtn.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						dialog.dismiss();
					}
				});
				break;
			case 0:
				application.setMenuSelectedTable(null);
				application.setMenuMainIsRefresh(true);
				dinerDishesCategoryIds=null;
				dinerDishes=null;
				dinerDishesCount=0;
				ActivityUtil.switchActivity(MainActivity.this, false, CartActivity.class);
				overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
				Toast("该餐台已经结账");
				break;
			case 2:
				ActivityUtil.switchActivity(MainActivity.this, false, CartActivity.class);
				overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
				break;
				default:
				break;
			}
		}
		
	};
	
	private String numStr;
	private Dialog dialog;
	protected boolean canScroll;
	public SoundMusicService soundService;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		Intent intent = new Intent(MainActivity.this,SoundMusicService.class);
		bindService(intent, connection, Context.BIND_AUTO_CREATE);
        init();
    }
    
    
	@SuppressWarnings("unchecked")
	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
	    	dinerDishesCategoryIds = intent.getStringArrayListExtra("dinerDishesCategoryIds");
	    	dinerDishes = (List<Dish>) intent.getSerializableExtra("dinerDishes");
	    	if(dinerDishes!=null && dinerDishes.size()>0){
	    		dinerDishesCount = getDinerDishesTotalNum(dinerDishes);
			}
	}
	
	@Override
	protected void loadData() {
		
		  ArrayList<String> dcIds = ordered_dish_dao.getdcIds();
	        
		    if(dinerDishesCategoryIds!=null){
		    	dcIds.addAll(dinerDishesCategoryIds);
		    }
  		dishCategory_dao.initDcdishesNum(this);
  	   synchronized (Constants.objectLock) {    
  		SQLiteDatabase db = this.openOrCreateDatabase(MenuDBHelper.DATABASE_NAME, Context.MODE_PRIVATE, null);
  	      	for(String dcIdStr:dcIds){
			updatedcDishNum(dcIdStr,db);
  	   	   }
      	dishCategoryDatas.clear();
          	dishCategoryDatas.addAll(dishCategory_util.init4DishesCategory());
          	dishCategoryDatas.addAll(dishCategory_dao.getDishesCategory());
		}
      	
      	dishDatas.clear();
      	dishDatas.addAll(dish_util.getTheDish(dishCategoryDatas.get(currentPosition).getCategoryId()));
		if(dinerDishes!=null && dinerDishes.size()>0){
			changeOrderNum(dinerDishes);
		}
		
		int dishesCount = ordered_dish_dao.getEffectiveCount();
    	numStr= String.valueOf((dinerDishesCount+dishesCount));
    	
	}
	
	@Override
	protected void describeView() {
		dishCategory_adapter.setDatas(dishCategoryDatas);
//		dishCategory_adapter.notifyDataSetChanged();
		
		mAdapter.setList(dishDatas,false);
//		mAdapter.notifyDataSetChanged();
//		mWaterfallView.setAdapter(mAdapter);
		
		dishAdapter = new DishAdapter(this, listener, dishDatas);
		dish_listView.setAdapter(dishAdapter);
		
        orderedNumTv.setText(numStr);
        if(dialog.isShowing()){
        	 dialog.dismiss();
        }
        setBlockScreen(false);
	}
	
	@Override
	protected void initCurrentView() {
		dialog = new Dialog(MainActivity.this, R.style.TransparentWindowStyle);
		View view = View.inflate(MainActivity.this, R.layout.wait_layout, null);
		dialog.show();
		dialog.setCanceledOnTouchOutside(false);
		dialog.setContentView(view);
		setBlockScreen(true);
		super.initCurrentView();
	}
    @Override
    protected void onResume() {
    	super.onResume();
		/*开去清理内存的service
		  */
    	if(application.isMenuMainIsRefresh()){
    		//2.2.0之后优化调整，对大量的数据的处理用子程序然后刷新界面的方法实现
    		initCurrentView();
    		    application.setMenuMainIsRefresh(false);
				       if(popWindow!=null && popWindow.isShowing()){
				    	   popWindow.dismiss();
				    	   popWindow = null;
				       }
    	}
//		if(bound){
//		clearMemoryService.clearMemory();
//		}
        sp= new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);//第一个参数为同时播放数据流的最大个数，第二数据流类型，第三为声音质量   
        music = sp.load(this, R.raw.change, 1); //把你的声音素材放到res/raw里，第2个参数即为资源文件，第3个为音乐的优先级   
       	if(application.getMenuSelectedTable()!=null &&application.getMenuSelectedTable().getTabNo()!=null){
        	tableNumTv.setText("餐台："+application.getMenuSelectedTable().getTabNo());
        	tablePeopleNumTv.setText("就餐人数："+application.getMenuSelectedTable().getPeopleCount()+"位");
    	}else{
    		tableNumTv.setText("餐台：");
        	tablePeopleNumTv.setText("就餐人数：");
    	}
       	btnisClicked=false;
    }
    
    protected void init(){
    	initUtil();
    	initUI();
		dialog = new Dialog(MainActivity.this, R.style.TransparentWindowStyle);
		View view = View.inflate(MainActivity.this, R.layout.wait_layout, null);
		dialog.show();
		dialog.setCanceledOnTouchOutside(false);
		dialog.setContentView(view);
		setBlockScreen(true);
    	Thread loadDataThread = new Thread(new Runnable() {
			
			@Override
			public void run() {
				initData();
				handler.sendEmptyMessage(Constants.DESCRIBE);
			}
		});
    	loadDataThread.start();
    }
    
    protected void initUtil(){
    	listener = new SpeedScrollListener();
        dishCategory_dao = MenuDishCategoryDAO.getInstance(MainActivity.this);
    	dish_dao = MenuDishDao.getInstance(this);
    	dishCategory_util = DishCategoryUtil.getInstance(this);
    	dish_util = DishUtil.getInstance(this);
    	ordered_dish_dao = MenuCartDao.getInstance(this);
    	application = KernalApplication.getInstance();
 //2.2.0       application.addActivity(MainActivity.this);
    	options  = ActivityMenuUtil.getImageOptions();
        imageLoader = ActivityMenuUtil.getImageLoader(this);
    	bdInterpolator =new BounceInterpolator();
    }
    
	public static void initImageLoader(Context context) {
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
				.threadPriority(Thread.NORM_PRIORITY - 2)
				.denyCacheImageMultipleSizesInMemory()
				.diskCacheFileNameGenerator(new Md5FileNameGenerator())
				.diskCacheSize(50 * 1024 * 1024) // 50 Mb
				.tasksProcessingOrder(QueueProcessingType.LIFO)
				.imageDownloader(new BaseImageDownloader(context))
				.writeDebugLogs() // Remove for release app
				.build();
		ImageLoader.getInstance().init(config);
	}
	
    protected void initData(){
    	dishCategoryDatas = new ArrayList<DishesCategory>();
    	synchronized (Constants.objectLock) {
            dishCategoryDatas.addAll(dishCategory_util.init4DishesCategory());
            dishCategoryDatas.addAll(dishCategory_dao.getDishesCategory());
		}
    	
    	dishAll = dish_dao.getDishesByParams(null);
    	dishNames = dish_util.switch2Arrays(dishAll);
    	
    	dishDatas = new ArrayList<Dish>();
    	dishDatas.addAll(dish_util.initDish(dishCategory_dao.getAll().get(0).getCategoryId()));
    }
    /*
     * 初始化控件
     * */
    protected void initUI() {
        
            exv1 = new ExplosionView(this);
            exv1.setVisibility(View.INVISIBLE);
            exv1.setBackgroundResource(R.anim.explosion);
            exa1 = (AnimationDrawable)exv1.getBackground();
                
        setContentView(R.layout.activity_main);
        l1 = (LinearLayout)findViewById(R.id.mainLy);
        mWaterfallView = (MultiColumnListView) findViewById(R.id.list);
        dishCategory_listView =  (ListView)findViewById(R.id.main_dishCategory_listView);
        searchDishActv = (AutoCompleteTextView)findViewById(R.id.main_search_dish);
        tableIcon = (ImageView)findViewById(R.id.main_table_icon);
        SettingIcon = (ImageView)findViewById(R.id.main_setting_icon);
        ListIcon = (ImageView)findViewById(R.id.main_list_icon);
        dish_listView =  (ListView)findViewById(R.id.dish_list);
        orderedNumTv = (BadgeView)findViewById(R.id.main_orderedNumTv);
        callServiceImv = (ImageView)findViewById(R.id.main_callservice);
        cartImv = (ImageView)findViewById(R.id.main_cart);
        listLy = (LinearLayout)findViewById(R.id.main_listLy);
         
        tableNumTv = (TextView)findViewById(R.id.main_table_number);
        tablePeopleNumTv =  (TextView)findViewById(R.id.main_people_number);
         
    }

//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        menu.add(Menu.NONE, PULL_TO_REFRESH_ID, 0, "启动<下拉刷新瀑布流>示例");
//        return super.onCreateOptionsMenu(menu);
//    }

    /*
     * 初始化控件意图
     * */
    protected void initUIAction() {
    	
        if(mWaterFlag){
       	 ListIcon.setImageResource(R.drawable.list_icon);
       	 mWaterfallView.setVisibility(View.VISIBLE);
       	 listLy.setVisibility(View.GONE);
       	 l1.setBackgroundResource(R.drawable.menu_bg);
        }else{
       	 ListIcon.setImageResource(R.drawable.picture_icon);
       	 listLy.setVisibility(View.VISIBLE);
       	 mWaterfallView.setVisibility(View.GONE);
    	 l1.setBackgroundResource(R.drawable.menu_list_bg);
        }
        
        /*
         * 菜肴的操作
         * */
    	mAdapter = new WaterfallAdapter(dishDatas, MainActivity.this);
        mWaterfallView.setAdapter(mAdapter);
        
        mWaterfallView.setOnLoadMoreListener(new OnLoadMoreListener() {
        	
        	
            @Override
            public void onLoadMore() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mWaterfallView.onLoadMoreComplete();
                    }
                }, 1000);
                
            }
        });
//        mWaterfallView.setOnTouchListener(new OnTouchListener() {
//			private float startY;
//			private float endY;
//			@Override
//			public boolean onTouch(View v, MotionEvent event) {
//				switch(event.getAction()){
//				case MotionEvent.ACTION_DOWN:
//					startY = event.getRawY();//getRawY()相对于屏幕的Y点坐标
//					break;
//				case MotionEvent.ACTION_UP:
//					endY = event.getRawY();
//					return false;
//					default:
//					break;
//				}
//				if(endY-startY<0){
//					canScroll=true;
//				}else{
//					canScroll=false;
//				}
//				return false;
//			}
//		});
        
        mWaterfallView.setOnScrollListener(new PLA_AbsListView.OnScrollListener() {
        	boolean isLastOne;
			@Override
			public void onScrollStateChanged(PLA_AbsListView view, int scrollState) {
				if(popWindow!=null && popWindow.isShowing()){
				    popWindow.dismiss();
			        popWindow = null;
				}
		           //正在滚动时回调，回调2-3次，手指没抛则回调2次。scrollState = 2的这次不回调    
	            //回调顺序如下    
	            //第1次：scrollState = SCROLL_STATE_TOUCH_SCROLL(1) 正在滚动    
	            //第2次：scrollState = SCROLL_STATE_FLING(2) 手指做了抛的动作（手指离开屏幕前，用力滑了一下）    
	            //第3次：scrollState = SCROLL_STATE_IDLE(0) 停止滚动             
	            //当屏幕停止滚动时为0；当屏幕滚动且用户使用的触碰或手指还在屏幕上时为1；  
	            //由于用户的操作，屏幕产生惯性滑动时为2  
	        
	            //当滚到最后一项且停止滚动时，执行加载    
//	            if (isLastOne && scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE && currentPosition<dishCategoryDatas.size()-1) {    
//	                //执行操作   
//	            	currentPosition = currentPosition+1;
//					dishCategory_listView.setSelection(currentPosition);
//					dishCategory_listView.smoothScrollToPosition(currentPosition);
//					dishCategory_adapter.setCurrentPosition(currentPosition);
//					dishCategory_adapter.notifyDataSetChanged();
//					dishCategoryId = dishCategoryDatas.get(currentPosition).getCategoryId();
//					
//				if(dishCategoryId.equals("all") ||dishCategoryId.equals("zpc") || dishCategoryId.equals("tjc")  || dishCategoryId.equals("tjcy") || dishCategoryId.equals("hytj")){
//					flag = false;
//				}else{
//					flag = true;
//					showsubCategory(dishCategory_listView.getChildAt(currentPosition-dishCategory_listView.getFirstVisiblePosition()));
//				}
//				upDishbyDc();
					
//					long availMemory = ActivityUtility.getAvailMemory(MainActivity.this);
//					long totalMemory = ActivityUtility.getTotalMemory(MainActivity.this);
//					Toast.makeText(MainActivity.this, "可用内存"+String.valueOf(availMemory)+"总内存"+String.valueOf(totalMemory), Toast.LENGTH_LONG).show();	
//	            	isLastOne = false;    
//	            } 
			}
			@Override
			public void onScroll(PLA_AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
//					if(firstVisibleItem+visibleItemCount==totalItemCount && totalItemCount>0 && canScroll){
//						isLastOne=true;
//					}
			}
		});
		
        /*
         * 菜肴列表的操作
         * */
        dishAdapter = new DishAdapter(MainActivity.this, listener, dishDatas);
        dish_listView.setAdapter(dishAdapter);
        /*
         * 菜类的操作
         * */
      try {
        dishCategory_listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if(!btnisClicked ){
					btnisClicked= true;
				subCategoryId = "";
				if(popWindow!=null && popWindow.isShowing()){
					popWindow.dismiss();
					popWindow = null;
				}
				isClicked = true;
				currentPosition = position;
				dishCategory_adapter.setCurrentPosition(position);
				dishCategoryId = dishCategoryDatas.get(position).getCategoryId();
				if(dishCategoryId.equals("all") ||dishCategoryId.equals("zpc") || dishCategoryId.equals("tjc")  || dishCategoryId.equals("tjcy") || dishCategoryId.equals("hytj")){
					flag = false;
				}else{
					flag = true;
					showsubCategory(view);
					mView = view;
				}
				upDishbyDc();
				btnisClicked= false;
				}else{
					ActivityUtil.Toast(MainActivity.this, "操作过于频繁请稍等......", false, false);
				}
			}
		});
  	} catch (Exception e) {
  		Log.e(LOG_TAG, "MessageQueue-JNI");
		e.printStackTrace();
	}
      
      try {
        dishCategory_listView.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if(popWindow!=null && popWindow.isShowing()){
				    popWindow.dismiss();
			        popWindow = null;
				}
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
	
			}
		});
		} catch (Exception e) {
	  		Log.i(LOG_TAG, "MessageQueue-JNI");
	  		e.printStackTrace();
		}
      
      try {
        dish_listView.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if(popWindow!=null && popWindow.isShowing()){
				    popWindow.dismiss();
			        popWindow = null;
				}
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				
			}
		});
  	} catch (Exception e) {
  		Log.i(LOG_TAG, "MessageQueue-JNI");
  		e.printStackTrace();
	}
        /*
         * 菜名的操作
         * */
		aTadapter = new AutoTextAdapater(dishNames, this,dish_dao);
		searchDishActv.setAdapter(aTadapter);
        searchDishActv.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				searchDishActv.setAdapter(aTadapter);
			}
		});
        
        searchDishActv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				//这个通知一定要加上，否则如果aTadapter处理的慢的话，没有通知到UI更新，这儿很容易报错退出。
				aTadapter.notifyDataSetChanged();
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				showMenuShowActivity(searchDishActv.getText().toString());
				searchDishActv.setText("");
			}
		});
        /*
         * 设置的操作
         * */
        SettingIcon.setOnClickListener(new OnClickListener() {
			private String username;
			private String password;
			@Override
			public void onClick(View v) {
				boolean isRemUser = (Boolean) SharedPreferencesUtils.getParam(MainActivity.this, Constants.MENU_IS_REM_CURRENTUSER, false);
				if(!isRemUser){
				final AlertDialog dialog = new AlertDialog.Builder(MainActivity.this).create();
				View view = View.inflate(MainActivity.this, R.layout.dialog_verifyid, null);
				dialog.setView(view,0,0,0,0);
				dialog.setCanceledOnTouchOutside(false);
				dialog.show();
				
				final EditText ID_Edt = (EditText)view.findViewById(R.id.verifyid_ID_edt);
				final EditText PD_Edt = (EditText)view.findViewById(R.id.verifyid_pw_edt);
				ImageView Cancel_Imv = (ImageView)view.findViewById(R.id.verifyid_cancle);
				Button LG_Btn = (Button)view.findViewById(R.id.verifyid_login_btn);
				final CheckBox isRemCb= (CheckBox)view.findViewById(R.id.verifyid_remId);
			    isRemCb.setChecked(isRemUser);
				isRemCb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
					
					@Override
					public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
						if(isRemCb.isChecked()){
							Toast.makeText(MainActivity.this, "记住登录状态,后续操作不用验证账号", Toast.LENGTH_SHORT).show();
						}else{
							Toast.makeText(MainActivity.this, "取消记住登录状态,后续操作验证账号", Toast.LENGTH_SHORT).show();
						}
					}
				});
				LG_Btn.setOnClickListener(new OnClickListener() {
					private int result;
					@Override
					public void onClick(View v) {
						 username = ID_Edt.getText().toString();
						 password = PD_Edt.getText().toString();
						 
							Thread loginThread = new Thread(new Runnable() {
								
								@Override
								public void run() {
									result = UserService.login(MainActivity.this, username, password, false);
								}
							});
							
							
						if(!username.equals("") && !password.equals("")){
							loginThread.start();
							try {
								loginThread.join();
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
                            if(result==0){
                            	ActivityUtil.Toast(MainActivity.this, "验证成功", false, false);
                            	ActivityUtil.switchActivity(MainActivity.this, false,  SettingActivity.class);
								dialog.dismiss();
								
								//把当前输入的账号密码记录到preference中
								SharedPreferencesUtils.setParam(MainActivity.this, Constants.USERNAME, username);
								SharedPreferencesUtils.setParam(MainActivity.this, Constants.PASSWORD, password);
								SharedPreferencesUtils.setParam(MainActivity.this, Constants.MENU_IS_REM_CURRENTUSER, isRemCb.isChecked());
							}else{
								ActivityUtil.Toast(MainActivity.this, "验证失败", false, false);
							}
						}else{
							ActivityUtil.Toast(MainActivity.this,  "用户名或密码为空", false, false);
						}
						
					}
				});
				Cancel_Imv.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						dialog.dismiss();
					}
				});
		}else{
				ActivityUtil.switchActivity(MainActivity.this, false, SettingActivity.class);
			}
			}
		});
        
        /*
         * 开台的操作 
         * */
        tableIcon.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(ActivityMenuUtil.checkNetworkState(MainActivity.this)){
					ActivityUtil.switchActivity(MainActivity.this, false, TableActivity.class);
					overridePendingTransition(R.anim.in_from_top, R.anim.out_to_bottom);
				}else{
					ActivityUtil.Toast(MainActivity.this, "请开启设备网络环境", false, false);
				}
			}
		});
        /*
         * 列表的操作
         * */
        ListIcon.setOnClickListener(new OnClickListener() {
			

			@Override
			public void onClick(View v) {
				mWaterFlag  = !mWaterFlag;
				initUIAction();
				dishCategory_adapter.setCurrentPosition(currentPosition);
			}
		});
        /*
         * 呼叫的操作
         * */
        callServiceImv.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(application.getMenuSelectedTable()==null){
					Toast( "请先开台再呼叫服务");
				}else{
					new CallService().execute(application.getMenuSelectedTable().getTabNo());
				}
			}
		});
        /*
         * 购物车的操作
         * */
        cartImv.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				final Message msg = handler.obtainMessage();
				//开启一个子线程去获取实时的餐台状态
				Thread getDinnerStatusThread = new Thread(new Runnable() {
					
					@Override
					public void run() {
						String status = TableService.getDinnerStatus(application.getMenuSelectedTable().getTabId());
						if(status.equals(DinnerStatusEnum.SETTLE.getCode())){
							msg.what=5;
						}else if(status.equals(DinnerStatusEnum.IDLE.getCode()))
						{
							msg.what=0;
						}else{
							msg.what=2;
						}
						handler.sendMessage(msg);
					}
				});
				if(!btnisClicked){
					btnisClicked=true;
					if(application.getMenuSelectedTable()!=null){
						getDinnerStatusThread.start();
					}else{
						ActivityUtil.switchActivity(MainActivity.this, false, CartActivity.class);
						overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
					}
				}else{
					ActivityUtil.Toast(MainActivity.this, "正在为您准备数据.....", false, false);
				}
			}
		});
        changorderNum();
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == PULL_TO_REFRESH_ID) {
        }
        return true;
    }

   
    
	public  void showMenuShowActivity(String categoryId,int position){
		Intent intent  = new Intent();
		intent.setClass(MainActivity.this, ShowActivity.class);
		intent.putExtra("categoryId", categoryId);
		intent.putExtra("position", position);
		intent.putExtra("dinerDishesCount", dinerDishesCount);
		startActivity(intent);
		overridePendingTransition(R.anim.in_from_bottom, R.anim.out_to_top);
		
	}
	
	public  void showMenuShowActivity(String dishName){
		Intent intent  = new Intent();
		intent.setClass(MainActivity.this, ShowActivity.class);
		intent.putExtra("dishName", dishName );
		startActivity(intent);
		overridePendingTransition(R.anim.in_from_bottom, R.anim.out_to_top);
	}
	
	public  void Toast(String content){
		LayoutInflater inflater = getLayoutInflater();
		View layout = inflater.inflate(R.layout.toast_layout,
		(ViewGroup) findViewById(R.id.toast_layout_root));

		ImageView image = (ImageView) layout.findViewById(R.id.image);
		image.setImageResource(R.drawable.toastimv);
		TextView text = (TextView) layout.findViewById(R.id.text);
		text.setGravity(Gravity.CENTER_VERTICAL);
		text.setText(content);

		Toast toast = new Toast(getApplicationContext());
		toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
		toast.setDuration(Toast.LENGTH_SHORT);
		toast.setView(layout);
		toast.show();
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(!isBlockScreen()){
		if(keyCode==KeyEvent.KEYCODE_BACK){
	        Dialog dialog = new AlertDialog.Builder(this). 
	                setTitle("您确定离开吗？"). 
	                setMessage("离开后购物车所有内容将清空"). 
	                setPositiveButton("确定", new DialogInterface.OnClickListener() { 
	                     
	                    @Override 
	                    public void onClick(DialogInterface dialog, int which) { 
	                    	    ordered_dish_dao.clearOrderDish();
	                    	    dish_dao.clearDishOrderNum();
	                    	    dishCategory_dao.clearDishNum();
	                    		MainActivity.this.finish();
//2.2.0	                    		setCurrentUser(null);
	                    		application.setBillNotes(null);
	                    		application.setMenuSelectedTable(null);
	                    		application.setMenuMainIsRefresh(false);
	                    		
	                    		currentPosition = 0;
	     				       if(popWindow!=null && popWindow.isShowing()){
	    				    	   popWindow.dismiss();
	    				    	   popWindow = null;
	    				       }
	     				       //主动销毁这个activity
	     				      onDestroy();
	                    } 
	                }). 
	                setNegativeButton("取消", new DialogInterface.OnClickListener() {
	                     
	                    @Override 
	                    public void onClick(DialogInterface dialog, int which) { 
	                    	dialog.dismiss();
	                    } 
	                }). 
	                create(); 
	        dialog.show();
		}
		return super.onKeyDown(keyCode, event);}
		else{
			return true;
		}
	}
	
	//更新菜类列表中菜肴的数量
	public void updatedcDishNum(String dcStrId,SQLiteDatabase db){
		dishCategory_dao.updateDcdishesNum(dcStrId,this,db);
	}
	
	
	private static long preserviceTime;
	private static long postserviceTime;
	public class CallService extends AsyncTask<String, Void, Boolean>{
			String tableNo;
			
		@Override
		protected void onPreExecute() {
		super.onPreExecute();
		preserviceTime = System.currentTimeMillis();
		}
			
		@Override
		protected Boolean doInBackground(String... params) {
			tableNo = params[0];
			if(preserviceTime-postserviceTime<30000)  {
				return false;
			}else{
				TableService.callService(tableNo,"6", "电子菜谱:"+tableNo+"号餐台呼叫现场服务!");
				return true;
			}
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
		      super.onPostExecute(result);
					if(!result){
						 Toast("您刚刚已经呼叫了服务,请稍候...");
					}else{
						 Toast("已呼叫服务员前来为您服务!");
					}
					postserviceTime = System.currentTimeMillis();
		      cancel(true);
		}
	}
	
	@Override
	protected void onStop() {
		super.onStop();
		sp.release();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(bound){
			unbindService(connection);
			bound = false;
		}
		
	}
	
	  private ServiceConnection connection = new ServiceConnection() {
			

			@Override
			public void onServiceDisconnected(ComponentName name) {
				bound = false;
			}
			
			@Override
			public void onServiceConnected(ComponentName name, IBinder service) {
				SoundMusicBinder binder = (SoundMusicBinder) service;
//				clearMemoryService  = binder.getService();
				soundService = binder.getService();
				bound = true;
			}
		};
	public String subCategoryId = "";
		
	    class ExplosionView extends ImageView{

            public ExplosionView(Context context) {
                    super(context);
            }
            //handle the location of the explosion
            public void setLocation(int top,int left){
                    this.setFrame(left, top, left+40, top+40);
            }        
}
	    
	    class LayoutListener implements OnTouchListener{ 

            public boolean onTouch(View v, MotionEvent event) {
                    exv1.setVisibility(View.INVISIBLE);
                    exa1.stop();
                    float x = event.getX();
                    float y = event.getY();
                    exv1.setLocation((int)y-20, (int)x-20);
                    exv1.setVisibility(View.VISIBLE);
                    exa1.start();
                    return false;
            }
	    }
	    
		public void setAnim(final View v, int[] start_location, int from) {
			ViewGroup anim_mask_layout = null;//动画层
			anim_mask_layout = ActivityMenuUtil.createAnimLayout(this);
			anim_mask_layout.addView(v);//把动画图片添加到动画层
			final View view = ActivityMenuUtil.addViewToAnimLayout(anim_mask_layout, v,
					start_location);//定义动画的开始位置
			int[] end_location = new int[2];// 这是用来存储动画结束位置的X、Y坐标
			cartImv.getLocationInWindow(end_location);// cartImv是那个购物车

			// 计算位移
			int endX = end_location[0] - start_location[0];// 动画位移的X坐标
			int endY = end_location[1] - start_location[1];// 动画位移的y坐标
			
			TranslateAnimation translateAnimationX = new TranslateAnimation(0,
					endX, 0, 0);
			
			TranslateAnimation translateAnimationY = new TranslateAnimation(0, 0,
					0, endY); 
//			AnticipateOvershootInterpolator AnticipateInterpolator  OvershootInterpolator 
			if(from==0){
				translateAnimationY.setInterpolator(bdInterpolator);
			}
			
			ScaleAnimation scaleAnimation = new ScaleAnimation(v.getScaleX(), 0.2f, v.getScaleY(), 0.2f);
			
			RotateAnimation rotateAnimation = new RotateAnimation(0, 360);
			
			AnimationSet set = new AnimationSet(false);
			set.setFillAfter(false);
			set.addAnimation(scaleAnimation);
			if(from==0){
				set.addAnimation(rotateAnimation);
			}
			set.addAnimation(translateAnimationY);
			set.addAnimation(translateAnimationX);
			set.setDuration(1000);
			
		view.startAnimation(set);
			// 动画监听事件
			set.setAnimationListener(new AnimationListener() {
				// 动画的开始
				@Override
				public void onAnimationStart(Animation animation) {
					v.setVisibility(View.VISIBLE);
					btnisClicked=true;
				}

				@Override
				public void onAnimationRepeat(Animation animation) {
				}

				// 动画的结束
				@Override
				public void onAnimationEnd(Animation animation) {
					v.setVisibility(View.GONE);
					
//			        String numStr = ordered_dish_dao.getCount();
//			        orderedNumTv.setText(numStr);
					changorderNum();
			        orderedNumTv.setBadgePosition(BadgeView.POSITION_TOP_RIGHT);
			        orderedNumTv.show();
			        
			        dishCategory_adapter.setDatas(dishCategoryDatas);
			        btnisClicked=false;
				}
			});
		}
		
		/*
		 * 单例模式构造popupWindow对象
		 * */
		private static PopupWindow pop;
		private static LinearLayout popwindowLy;
		public static PopupWindow getPop(){
			if(pop==null){
				pop = new PopupWindow();
			}
			return pop;
		}
		public static LinearLayout getPopLy(Context context){
				popwindowLy=null;
				popwindowLy = new LinearLayout(context);
				popwindowLy.setOrientation(LinearLayout.VERTICAL);
				popwindowLy.setBackgroundResource(R.drawable.sub_dc_bg);
				LayoutParams pa = new LayoutParams(ActivityUtil.dip2px(context, 147), LayoutParams.WRAP_CONTENT);
				popwindowLy.setLayoutParams(pa);
			return popwindowLy;
		}
		/*
		 * 处理二级分类的显示
		 * */
		
		public void showsubCategory(View view){
			//处理二级菜肴分类弹出popwindow
			List<DishesCategory> subDishesCategories = dishCategory_dao.getsubDishesCategory(dishCategoryId);
			if(subDishesCategories.size()>0){
				popwindowLy = getPopLy(MainActivity.this);
				for(int i=0;i<subDishesCategories.size();i++){
					final DishesCategory subDishesCategory = subDishesCategories.get(i);
					FrameLayout fl = new FrameLayout(MainActivity.this);
					TextView tv = new TextView(MainActivity.this);
					tv.setPadding(8, 8, 8, 8);
					tv.setTextSize(18);
					tv.setText(subDishesCategory.getCategoryName());
					tv.setTextColor(getResources().getColor(R.color.nearwhite));
					tv.setGravity(Gravity.CENTER);
					tv.setOnClickListener(new OnClickListener() {
						
						@Override
						public void onClick(View v) {
							subCategoryId = subDishesCategory.getCategoryId();
							dishDatas = dish_util.getTheDish(subCategoryId);
							
							if(dinerDishes!=null && dinerDishes.size()>0){
								changeOrderNum(dinerDishes);
							}
							
//							mAdapter = new WaterfallAdapter(dishDatas, MainActivity.this);
//							mWaterfallView.setAdapter(mAdapter);
							mAdapter.setList(dishDatas,false);
//							mAdapter.notifyDataSetChanged();
//							mWaterfallView.setAdapter(mAdapter);
							
							dishAdapter = new DishAdapter(MainActivity.this, listener, dishDatas);
							dish_listView.setAdapter(dishAdapter);
						}
					});
					fl.addView(tv);
					
					TextView img = new TextView(MainActivity.this);
					img.setId(0);
					LayoutParams params = new LayoutParams(30, 30);
					img.setLayoutParams(params);
					img.setTextColor(Color.WHITE);
					img.setTextSize(18);
					img.setBackgroundResource(drawable.redpoint);
					img.setGravity(Gravity.CENTER);
					
					int num = subDishesCategory.getDishNum();
					if(num>0){
						img.setVisibility(View.VISIBLE);
						img.setText(String.valueOf(num));
					}else{
						img.setVisibility(View.INVISIBLE);
					}
					
					TextView line = new TextView(this);
					LayoutParams param =  new LayoutParams(LayoutParams.MATCH_PARENT, 1);
					line.setLayoutParams(param );
					line.setBackgroundResource(R.drawable.sub_dv_bg);
					line.setGravity(Gravity.BOTTOM);
					
					fl.addView(line);
					fl.addView(img);
					fl.findViewById(0).setTranslationX(20);
					fl.findViewById(0).setTranslationY(15);
					popwindowLy.addView(fl);
				}
				popWindow = getPop();
				popWindow.setContentView(popwindowLy);
				popWindow.setWidth(LayoutParams.WRAP_CONTENT);
				popWindow.setHeight(LayoutParams.WRAP_CONTENT);
				popWindow.setOutsideTouchable(true);
				if(view!=null){
					int[] location = new int[2];
					view.getLocationOnScreen(location);
					popWindow.showAtLocation(view, Gravity.NO_GRAVITY, location[0]+view.getWidth()+20, location[1]);
				}else{
					Toast("弹出子分类列表失败!");
				}
				}
		}
		
		public void updatesubCategory(){
		       if(popWindow!=null && popWindow.isShowing()){
		    	   popWindow.dismiss();
		    	   popWindow = null;
		       }
		       showsubCategory(mView);
		}
		    
		@Override
		protected void onPause() {
			super.onPause();
			subCategoryId="";
			imageLoader.clearMemoryCache();
			imageLoader.clearDiskCache();
			dinerDishesCount=0;
			if(MainActivity.this.dialog!=null && MainActivity.this.dialog.isShowing()){
				 MainActivity.this.dialog.dismiss();
			}
		       if(popWindow!=null && popWindow.isShowing()){
		    	   popWindow.dismiss();
		    	   popWindow = null;
		       }
		}
		
		//购物车图标显示的菜肴数量
		private void changorderNum(){ 
			int dishesCount = ordered_dish_dao.getEffectiveCount();
	    	String numStr= String.valueOf((dinerDishesCount+dishesCount));
            orderedNumTv.setText(numStr);
		}
		//处理账单菜肴的已点菜肴数量信息，加入本地数据中
		private void changeOrderNum(List<Dish> dinerDishes){
			for(Dish dinerDish:dinerDishes){
				for(Dish dish:dishDatas){
					if(dinerDish.getDishesId().equals(dish.getDishesId())){
						int m = (int) dinerDish.getOrdersalenum();
						int n = dish.getDishorderNum();
						dish.setDishorderNum(m+n);
						break;
					}
				}
			}
		}

		//取出账单菜肴的所有的数量，用于显示在购物车图标上
		private int getDinerDishesTotalNum(List<Dish> dinerDishes){
			int totalNum=0;
			for(Dish dinerDish:dinerDishes){
				if(!dinerDish.getDishesStatus().equals("2")){
					int num = (int) dinerDish.getOrdersalenum();
					totalNum = totalNum+num;
				}
			}
			return totalNum;
		}
	
	/**
	 * 但菜类的listview被点击或改变时相对应的菜数据和控件刷新更改的方法
	 * */
		private void upDishbyDc(){
			dialog = new Dialog(MainActivity.this, R.style.TransparentWindowStyle);
			View view = View.inflate(MainActivity.this, R.layout.wait_layout, null);
			dialog.show();
			dialog.setCanceledOnTouchOutside(false);
			dialog.setContentView(view);
			setBlockScreen(true);
			super.reInitCurrentView();
		}
		
		@Override
		protected void reLoadData() {
			dishDatas.clear();
			dishDatas.addAll(dish_util.getTheDish(dishCategoryId));
			
			if(dinerDishes!=null && dinerDishes.size()>0){
				changeOrderNum(dinerDishes);
			}
		}
		
		@Override
		protected void reDescribeView() {
			if(mWaterFlag){
				mAdapter.setList(dishDatas,true);
//				mAdapter.notifyDataSetChanged();
//				mWaterfallView.setAdapter(mAdapter);
//				mAdapter = new WaterfallAdapter(dishDatas, this);
//				mWaterfallView.setAdapter(mAdapter);
			}else{
				dishAdapter = new DishAdapter(MainActivity.this, listener, dishDatas);
				dish_listView.setAdapter(dishAdapter);
			}
	        if(dialog.isShowing()){
	        	 dialog.dismiss();
	        }
	        setBlockScreen(false);
		}
}
